package top.catchcat.blogs.controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import top.catchcat.blogs.dao.blogs.Blog;
import top.catchcat.blogs.dao.userIfo.User;
import top.catchcat.blogs.service.impl.BlogServiceImpl;
import top.catchcat.blogs.service.impl.LoginServiceImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Controller
public class IndexController {

    @Autowired
    private LoginServiceImpl loginService;

    @Autowired
    private BlogServiceImpl blogService;

    @GetMapping("/")
    public String index(HttpServletRequest request, Model model,
                        @RequestParam(value = "sort", defaultValue = "new", required = false) String sort,
                        @RequestParam(name = "search", required = false) String search,
                        @RequestParam(name = "tag", required = false) String tag,
                        @RequestParam(name = "sortName", defaultValue = "最新", required = false) String sortName,
                        @RequestParam(value = "page", defaultValue = "1") int page) {
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("token")) {
                        String token = cookie.getValue();
                        User userByToken = loginService.getUserByToken(token);
                        if (userByToken != null) request.getSession().setAttribute("user", userByToken);
                        break;
                    }
                }
            }
        }
        PageInfo<Blog> allBlogs = blogService.getAllBlogs(search, tag, sort, page, 2);
        model.addAttribute("allBlogs", allBlogs);
        model.addAttribute("search", search);
        model.addAttribute("tag", tag);
//        model.addAttribute("tags", tags);
        model.addAttribute("sort", sort);
        model.addAttribute("sortName", sortName);
        System.out.println("search:"+ search+" tag:"+ tag+" sortName:"+sortName+" sort:"+sort);
        return "index";
    }

    @GetMapping("/blog/{id}")
    public String indexQuestion(@PathVariable Long id, Model model){
        Blog blogById = blogService.getBlogById(id,true);
        model.addAttribute("blog",blogById);
        return "blog";
    }
}
